<?php

namespace app\model;

use think\Model;

class TransferBackRecord extends Model
{
    // 设置当前模型对应的数据表
    protected $name = 'transfer_back_record';
    // 设置当前模型主键
    protected $pk = 'id';

    // 添加/修改
    public function edit($params)
    {
        if (empty($params['id'])) {
            $data = $this::create($params);
            return $data->id;
        }
        $this::update($params);
        return $params['id'];
    }

    /**
     * 根据条件获取一条数据
     * 
     * @dateTime 2022/09/17
     * @author zhixiang0215@126.com
     * @param array where 查询条件
     * @param string fields 查询字段
     * @return array
     */
    public function getInfoByWhere($where = [], $fields = 'id')
    {
        $data = $this::where($where)->field($fields)->find();
        return $data ? $data->toArray() : [];
    }

    // 根据条件批量获取数据
    public function getBatchDataByWhere($where = [], $fields = 'id')
    {
        $data = $this::where($where)->field($fields)->select();
        return $data ? $data->toArray() : [];
    }

    // 根据条件获取分页数据
    public function getPagingDataByWhere($where = [], $page = 1, $limit = 10, $fields = 'id', $order = 'id desc')
    {
        $total = $this::where($where)->count();

        if ($total == 0) return ['total' => 0, 'total_page' => 0, 'data' => []];

        $offset = ($page - 1) * $limit;
        if ($offset < 0) $offset = 0;

        $totalPage = ceil($total / $limit);

        $data = $this::where($where)->field($fields)->order($order)->limit($offset, $limit)->select()->toArray();

        return ['total' => $total, 'total_page' => $totalPage, 'data' => $data];
    }
}